package com.ssms.service;

import com.ssms.commons.Result;
import com.ssms.commons.TablePage;
import com.ssms.dao.ClazzMapper;
import com.ssms.dao.SubjectMapper;
import com.ssms.model.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SubjectService {

    @Resource
    private SubjectMapper subjectMapper;
    @Resource
    private ClazzMapper clazzMapper;
    
    public Result saveSubject(Subject subject) {
        Result check = check(subject);
        if (check != null) {
            return check;
        }

        int count = subjectMapper.insertSelective(subject);
        return count > 0?Result.success():Result.failed("添加失败", 500);
    }


    public TablePage search(TablePage tablePage, String val) {
        int size = tablePage.getLimit();
        int start = (tablePage.getPage() - 1) * size;
        // 获取分页数据
        List<Subject> roles = subjectMapper.selectPage(start, size, val);
        // 获取符合条件的总数
        int count = subjectMapper.selectPageCount(val);
        tablePage.setCount(count);
        tablePage.setData(roles);
        return tablePage;
    }

    // 校验专业名和编号不能重复
    private Result check(Subject subject){
        Subject obj = subjectMapper.selectByName(subject.getSubjectName());
        if (obj != null && subject.getId() != obj.getId()) {
            return Result.failed("专业名称已存在", 500);
        }

        obj = subjectMapper.selectByNo(subject.getSubjectNo());
        if (obj != null && subject.getId() != obj.getId()) {
            return Result.failed("专业编号已存在", 500);
        }

        return null;
    }

    public Result update(Subject subject) {
        Result check = check(subject);
        if (check != null) {
            return check;
        }

        int count = subjectMapper.updateByPrimaryKeySelective(subject);
        return count > 0?Result.success():Result.failed("更新失败", 500);
    }

    public Result delete(Integer id) {
//        int i = clazzMapper.selectBySubjectIdCount(id);
//        if(i > 0){
//            Result.failed("该专业存在班级，不能删除", 500);
//        }

        int count = subjectMapper.deleteByPrimaryKey(id);
        return count > 0?Result.success():Result.failed("删除失败", 500);
    }

    public Result all() {
        return Result.success(subjectMapper.selectAll());
    }

    public Result getByAcademyId(Integer academyId){
        List<Subject> subjects = subjectMapper.selectByAcademyId(academyId);
        return Result.success(subjects);
    }

    public Result query(Integer id) {
        return Result.success(subjectMapper.selectByPrimaryKey(id));
    }
}
